package fallon;

import com.adxon.MsgException;
import com.adxon.Uri;
import com.adxon.cookie.Station;
import com.adxon.data.Base;
import com.adxon.servlet.ServletBase;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class FallonServlet extends ServletBase{
	/*private void all(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		StringBuilder b=new StringBuilder("[");
		Collection o=new Collection();
		PreparedQuery r=Collection.query(o);
		boolean k=true;
		for(Entity e:r.asIterable()){
			o=new Collection();
			try {
				o.update(e);
			} catch (MsgException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if(!k)
				b.append(',');
			b.append("{\"_\":\"/image/");
			b.append(o.getId());
			b.append(".s.jpg\",\"r\":");
			b.append(o.getRate());
			if(k){
				b.append(",\"k\":");
				b.append(System.currentTimeMillis());
				k=false;
			}
			b.append("}");
		}
		if(b.length()==1)
			b.append("{\"k\":0}");
		b.append(']');
		resp.setContentType("text;charset=utf-8");
		resp.getWriter().print(b);
	}
	public void doGet(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		String p=req.getPathInfo();
		System.out.println("Fallon: "+p);
		if(p.equals("") || p.equals("/"))
			forward("fallon.jsp",req,resp);
		else{
			//Kooky.getAll(req);
			Station a=Station.get(req);
			if(a!=null){
				Uri u=new Uri(p);
				long i=a.getOwnerId();
				if(i==0){
					Base e=a.getSession();
					i=e.getId();
				}
				String x=u.getExtension();
				if(x.equals(".all"))
					all(req,resp);
				else if(x.equals(".jpg"))
					try {
						jpg(req,resp,i+"/"+u.getId(),u.getType());
					} catch (MsgException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				else if(x.equals(".json")){
					String k=req.getParameter("k");
					long t=k==null?0:Long.parseLong(k);
					long m=System.currentTimeMillis();
					System.out.println(t+"\n"+a.getTime());
					if(t>a.getTime() && m-t+t%3600000<7200000){	// round to hours
						resp.setStatus(304);
						return;
					}
					Collection.refresh(i);
					if(u.getId().equals("r"))
						recyclebin(req,resp,i,t,m);
					else try{
						outfit(req,resp,i,t,m);
					}catch(MsgException e){
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else if(x.equals(".manifest"))
					manifest(req,resp,i);
				else if(x.equals(".rate"))
					try{
						rate(req,resp,i);
					}catch(MsgException e){
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				else if(x.equals(".test")){
					setAttributes(req,null);
					req.setAttribute("Path",i+"/"+u.getId());
					forward("test.jsp",req,resp);
				}else forward404(req,resp);
			}else a=new Station();
			a.addTo(resp);
		}
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		doGet(req,resp);
	}
	private void jpg(HttpServletRequest req,HttpServletResponse resp,
			String path,String type) throws IOException,ServletException,MsgException{
		Collection c=Collection.create(path,type);
		if(c==null)
			forward404(req,resp);
		else{
			cacheControl(resp,360000);	// 100 hours
			resp.setContentType(c.getContentType());
			resp.getOutputStream().write(c.getBits());
		}
	}
	private void manifest(HttpServletRequest req,HttpServletResponse resp,
			long owner) throws IOException,ServletException{
		setAttributes(req,null);
		Collection o=new Collection();
		o.setOwner(owner);
		PreparedQuery r=Collection.query(o);
		StringBuilder b=new StringBuilder();
		for(Entity t:r.asIterable(FetchOptions.Builder.withLimit(20))){
			o=new Collection();
			try {
				o.update(t);
			} catch (MsgException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			b.append('\n');
			b.append(o.getId());
			b.append(".jpg");
		}
		req.setAttribute("Article",b.toString());
		forward("manifest.jsp",req,resp);
	}
	private void outfit(HttpServletRequest req,HttpServletResponse resp,
			long owner,long time,long current) throws IOException,MsgException{
		StringBuilder b=new StringBuilder("[");
		Collection o=new Collection();
		o.setOwner(owner);
		PreparedQuery r=Collection.query(o);
		boolean k=true;
		for(Entity e:r.asIterable()){
			o=new Collection();
			o.update(e);
			int a=o.getRate();
			if(a>99 || a<12)
				continue;
			else if(a<15 && o.getCreateTime()<time){
				o.setRate(10);
				o.commit();
				continue;
			}
			if(!k)
				b.append(',');
			b.append("{\"_\":\"");
			b.append(o.getId());
			b.append(".jpg\",\"r\":");
			b.append(o.getRate());
			if(k){
				b.append(",\"k\":");
				b.append(current);
				b.append(",\"w\":\"<ul><li>Hangzhou<br>Cloud<div style=font-size:38px>13��</div><li>Afernoon<br><img src=/img/cloud4.svg><br>22��/10��<li>Evening<br><img src=/img/cloud4.svg><br>22��/10��<li>Night<br><img src=/img/cloud4.svg><br>22��/10��<li>Tomorrow<br><img src=/img/cloud4.svg><br>22��/10��</ul>\"");
				k=false;
			}
			b.append("}");
		}
		if(b.length()==1)
			b.append("{\"k\":0}");
		b.append(']');
		resp.setContentType("text;charset=utf-8");
		resp.getWriter().print(b);
	}
	private void rate(HttpServletRequest req,HttpServletResponse resp,
			long owner)throws IOException,ServletException,MsgException{
		resp.setContentType("text/plain");
		String b="Bad";
		String i=req.getParameter("i");
		String r=req.getParameter("r");
		if(i!=null && r!=null){
			Uri u=new Uri(i);
			Collection c=new Collection();
			c.setPermaLink(owner+"/"+u.getId());
			c.update();
			byte t=c.getRate();
//			if(t<11 || t>99)
//				c.setCreateTime(0);
			byte y=Byte.parseByte(r);
			if(t>17)
				y=(byte)(y>20?60:19);
			else y=(byte)(y>14?16:13);
			c.setRate(y);
			c.commit();
			if(r.equals("19")){
				Candidate a=new Candidate();
				a.setPermaLink(u.getId());
				try{
					a.update();
				}catch(MsgException e){
					a.setId(c);
					a.setOwner(owner);
					a.commit();
				}
			}
			b="Ok";
		}
		print(resp,b);
	}
	private void recyclebin(HttpServletRequest req,HttpServletResponse resp,
			long owner,long time,long current) throws IOException{
		StringBuilder b=new StringBuilder("[");
		Collection o=new Collection();
		o.setOwner(owner);
		PreparedQuery r=Collection.query(o);
		boolean k=true;
		for(Entity e:r.asIterable()){
			o=new Collection();
			try {
				o.update(e);
			} catch (MsgException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			int a=o.getRate();
			if(a>99 || a<12 || (a<15 && o.getCreateTime()<time)){
				if(!k)
					b.append(',');
				b.append("{\"_\":\"");
				b.append(o.getId());
				b.append(".s.jpg\",\"r\":");
				b.append(o.getRate());
				if(k){
					b.append(",\"k\":");
					b.append(current);
					b.append(",\"w\":\"<ul><li>Hangzhou<br>Cloud<div style=font-size:38px>13��</div><li>Afernoon<br><img src=/img/cloud4.svg><br>22��/10��<li>Evening<br><img src=/img/cloud4.svg><br>22��/10��<li>Night<br><img src=/img/cloud4.svg><br>22��/10��<li>Tomorrow<br><img src=/img/cloud4.svg><br>22��/10��</ul>\"");
					k=false;
				}
				b.append("}");
			}
		}
		if(b.length()==1)
			b.append("{\"k\":0}");
		b.append(']');
		resp.setContentType("text;charset=utf-8");
		resp.getWriter().print(b);
	}*/
}